<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/17
 * Time: 16:08
 */

namespace app\wechat\service;


use app\common\model\UserFavorite;
use app\common\service\BaseService;

class UserFavoriteService extends BaseService
{
    private static $user_favorite;

    public function __construct()
    {
        self::$user_favorite = new UserFavorite();
    }

    /**
     * @param $data
     * @return array
     * 收藏文章
     */
    public static function saveUserFavorite($data)
    {
        new self();
        $where =
            [
                'user_id' => $data['user_id'],
                'article_id' => $data['article_id'],
            ];
        $list = self::$user_favorite->getOneInfo($where);
        if (empty($list)) {
            //未收藏
            $res = self::_addUserFavorite($data);
            $return = self::boolMsg($res, 'favorite');
        } else {
            if ($list['is_del'] == 1) {
                //已删除收藏 重新收藏
                $res = self::_updateUserFavorite($list['id']);
                $return = self::boolMsg($res, 'favorite');
            } else {
                //已收藏
                $return = self::msg('FAVORITE_REPEAT_SUCCESS');
            }
        }
        return $return;
    }

    /**
     * @param $data
     * @return int|string
     * 添加收藏
     */
    public static function _addUserFavorite($data)
    {
        $addData =
            [
                'user_id' => $data['user_id'],
                'article_id' => $data['article_id'],
                'is_del' => '0',
            ];
        $res = self::$user_favorite->insertData($addData);
        return $res;
    }

    /**
     * @param $id
     * @return bool
     */
    public static function _updateUserFavorite($id)
    {
        $bool = false;
        $saveData =
            [
                'is_del' => '0',
                'update_time' => date('Y-m-d H:i:s'),
            ];
        $res = self::$user_favorite->updateData(['id' => $id], $saveData);
        if ($res !== false) {
            $bool = true;
        }
        return $bool;
    }


}